package cn.edu.scau.cmi.maintain.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.domain.Address;
import cn.edu.scau.cmi.ema.domain.Adultertype;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Food;
import cn.edu.scau.cmi.ema.domain.Foodbatch;
import cn.edu.scau.cmi.ema.domain.Foodtype;
import cn.edu.scau.cmi.ema.domain.Picture;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.service.base.EntityFactoryService;
import cn.edu.scau.cmi.ema.util.ExcelUtil;
import cn.edu.scau.cmi.ema.util.SegmenterUtil;
import cn.edu.scau.cmi.ema.util.CmiSetUtil;
import cn.edu.scau.cmi.front.controller.FrontCmiEmaController;
import cn.edu.scau.cmi.front.dao.CmiEventDAO;
import cn.edu.scau.cmi.front.dao.CmiPictureDAO;
import cn.edu.scau.cmi.front.domain.FuzzyAddress;
import cn.edu.scau.cmi.front.domain.FuzzyFoodtype;
import cn.edu.scau.cmi.front.service.CmiFoodTypeIdService;
import cn.edu.scau.cmi.front.service.FuzzyAddressService;

/**
 * 没什么用的方法，待确认后逐步删除
 * 
 */

@Controller("MaintainFoodtypeController")

//@PropertySource(value = { "classpath:food2type.properties" })

public class MaintainFoodtypeController extends FrontCmiEmaController {
	
	private String testWorkbook = "E:\\Workspace\\git\\ema\\ema\\项目文档\\静态适配数据\\（5）静态适配数据-张星联地址自动适配测试.xlsx";
//	private String testOutputWorkbook = "E:\\Workspace\\git\\ema\\ema\\项目文档\\静态适配数据\\（5）静态适配数据-张星联地址自动适配测试-输出文件.xlsx";
	

	
//	从电子表格中列出所有的需要匹配的食物的类型，并将结果填写到电子表格中，后期可以导入到数据库中。
	@RequestMapping("/listRows4MatchedFoodtypes")
	@Transactional(timeout=300000000)
	public ModelAndView listRows4MatchedFoodtypes(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		List<FuzzyFoodtype> fuzzyFoodtypeList = new ArrayList<FuzzyFoodtype>();
		
//
//			page = new CmiPagination(eventService.countEvents());
//		}
		
		Workbook workbook = ExcelUtil.getWorkbook(testWorkbook);
		Sheet sheet = workbook.getSheetAt(0);
		int lastRowNum = sheet.getLastRowNum();
		
//		每一行中的地址字符串封装为一个FuzzyFoodtype对象
//		从第二行开始是数据，每次处理100条数据。
		
		
		for(int rowNum=2, quantity =0; rowNum<lastRowNum && quantity< 100;rowNum++, quantity++) {
			
			int isFoodtypeDealedColumn = 21;//是否已经处理的列，空格或者0表示没有处理，1表示已经处理了。
			Row eventRow = sheet.getRow(rowNum);
			Cell isFoodtypeDealedCell = eventRow.getCell(isFoodtypeDealedColumn);
			String isFoodtypeDealed = ExcelUtil.getCellValue(isFoodtypeDealedCell);
			if(isFoodtypeDealed.equals("1")) {
				continue;
			}
			
			FuzzyFoodtype fuzzyFoodtype = new FuzzyFoodtype();
			
			fuzzyFoodtype.setRowNumber(rowNum);
			
			int fuzzyFoodColumn = 2;//原始的食物所在的列
			Cell fuzzyFoodCell = eventRow.getCell(fuzzyFoodColumn);
			String fuzzyFoodName = ExcelUtil.getCellValue(fuzzyFoodCell);
			fuzzyFoodtype.setFoodName(fuzzyFoodName);
			
			int fuzzyFoodtypeColumn = 12;//原始的食物类别所在的列
			Cell fuzzyFoodtypeCell = eventRow.getCell(fuzzyFoodtypeColumn);
			String fuzzyFoodtypeName = ExcelUtil.getCellValue(fuzzyFoodtypeCell);
			fuzzyFoodtype.setFoodtypeName(fuzzyFoodtypeName);
			
			fuzzyFoodtypeList.add(fuzzyFoodtype);
		}
	
//		mav.addObject("page", page);
		mav.addObject("fuzzyFoodtypeList", fuzzyFoodtypeList);
		mav.setViewName("maintance/listRows4MatchedFoodtypes.jsp");
		return mav;
	}
	
	
//	获取单个的地址的匹配情况，返回json数据，请求数据是地址的分词字符串，中间使用空格连接
	@RequestMapping(value = "/restGetFoodtypeByFoodName/{fuzzyFoodName}", method = RequestMethod.GET)
	@ResponseBody
	@Transactional(timeout=300000000)
//	@Value("#{food2type}")，在ApplicationContext
	public Object restGetFoodtypeByFoodName(HttpServletRequest request, @PathVariable String fuzzyFoodName) {
//		首先从map中获取类型，如果类型没有获取，就从数据库中查找包含这个词的类型，并将结果作为json返回给前端
		
		Set<Foodtype> foodtypes = cmiFoodtypeService.fuzzyMatchFoodtype(fuzzyFoodName);
		
		CmiPsonService cmiPsonService = new CmiPsonService();
		CmiPagination cmiPagination = new CmiPagination();
		return JSONObject.parse(cmiPsonService.toPsonString(foodtypes, 2, cmiPagination));
	}
	
	
//	<a herf="/restSaveFuzzyAddress/826771">张沟村：亚洲中国湖北省省直辖县级行政区划仙桃市张沟镇张沟村</a>
//	将页面中选中的结果保存到电子表格中
//	rowNumber: 电子表格中的行号；addressId：本地地址的id； baiduMatchAddressName：百度匹配的地址 
	
	@RequestMapping(value = "/restSaveFoodtypeIntoExcel/{rowNumber}/{foodName}/{selectFoodtypeIdByFoodName}/{selectFoodtypeIdByFoodtypeName}", method = RequestMethod.GET)
	@ResponseBody
	@Transactional(timeout=300000000)
	public Object restSaveFoodtypeIntoExcel(HttpServletRequest request, @PathVariable int rowNumber, @PathVariable String foodName, @PathVariable int selectFoodtypeIdByFoodName, @PathVariable int selectFoodtypeIdByFoodtypeName) throws Throwable {
		int idDealedfoodtypeColumn = 21;//第12列是否已经处理食品类型
		int foodtypeNameByFoodNameColumn = 22;//第22列是根据食物名称确定的食物类型
		int foodtypeNameByFoodtypeNameColumn = 23;//第23列是根据食物类型名称确定的食物类型

		Workbook workbook = ExcelUtil.getWorkbook(testWorkbook);
		Sheet sheet = workbook.getSheetAt(0);
		Row row = sheet.getRow(rowNumber);
		Map<Integer, String> valueMap = new HashMap<Integer, String>();
		valueMap.put(idDealedfoodtypeColumn, "1");//已经处理
		valueMap.put(foodtypeNameByFoodNameColumn, foodtypeDAO.findFoodtypeById(selectFoodtypeIdByFoodName).getName());
		valueMap.put(foodtypeNameByFoodtypeNameColumn, foodtypeDAO.findFoodtypeById(selectFoodtypeIdByFoodtypeName).getName());
		
		ExcelUtil.saveRow(testWorkbook, row, valueMap);
		//保存后，将食物的类型保存到数据库中，方便后面的使用，食物的名称不应该有多个记录，是唯一的记录
//		Food existingFood = CmiSetUtil.getSoleInstance(foodDAO.findFoodByName(foodName));
//		如果不存在这个食物，保存，存在，且食物类型就是所选择的食物类型，就不用处理。
		
		Food food = entityFactoryService.initFood();
		
		food.setName(foodName);
		food.setFoodtype(foodtypeDAO.findFoodtypeById(selectFoodtypeIdByFoodName));
		foodService.saveFood(food);
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "SUCCESS");
		
		return jsonObject;
	}
	

}